from django.shortcuts import render
from django.views import View
from django import http
import json, re
from django.contrib.auth import login, authenticate, logout
from meiduo_mall.settings.dev import logger
from django_redis import get_redis_connection
from celery_tasks.email.tasks import send_email_verify_url

from apps.users.models import User
from meiduo_mall.utils.views import LoginRequiredJSONMixin
from apps.users.utils import generate_email_verify_url, check_email_verify_url


# Create your views here.
# 激活邮箱
class EmailActiveView(View):
    """验证激活邮箱
    PUT /emails/verification/
    """
    def put(self, request):
        # 接收参数
        token = request.GET.get('token')

        # 校验参数
        if not token:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少token'})

        # 实现核心逻辑
        # 通过token提取要验证邮箱的用户
        user = check_email_verify_url(token=token)
        if not user:
            return http.JsonResponse({'code': 400, 'errmsg': '无效的token'})

        # 将要验证邮箱的用户的email_active字段设置True
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '邮箱验证失败'})

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': '邮箱验证成功'})


# 添加邮箱
class EmailView(LoginRequiredJSONMixin, View):
    """添加邮箱
    PUT /emails/
    """
    def put(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')

        # 校验参数
        if not email:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        # 校验邮箱格式
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.JsonResponse({'code': 400, 'errmsg': '参数email格式错误'})

        # 添加邮箱就是将用户填写的邮箱地址保存到当前登录用户的email字段
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '添加邮箱失败'})

        # 发送邮箱的验证激活邮件：耗时操作，不能让他阻塞主逻辑，需要从主逻辑中解耦出来，celery
        # verify_url = '测试的激活链接'
        verify_url = generate_email_verify_url(user=request.user)
        send_email_verify_url.delay(email, verify_url)

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': 'OK'})


# 用户中心
class UserInfoView(LoginRequiredJSONMixin, View):
    """用户中心"""
    def get(self, request):
        data_dict = {
            'code': 0,
            'errmsg': 'OK',
            'info_data': {
                'username': request.user.username,
                'mobile': request.user.mobile,
                'email': request.user.email,
                'email_active': request.user.email_active
            }
        }
        return http.JsonResponse(data_dict)


# 用户退出
class LogoutView(View):
    """退出登录"""
    def delete(self, request):
        # 清理登录状态
        logout(request)
        # 清理用户名cookie
        response = http.JsonResponse({'code': '0', 'errmsg': '退出登录成功'})
        response.delete_cookie('username')
        # 返回响应
        return response


# 用户登录
class LoginView(View):
    """用户登录"""
    def post(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        username = json_dict.get('username')
        password = json_dict.get('password')
        remembered = json_dict.get('remembered')

        # 校验参数
        if not all([username, password]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': '参数password格式错误'})

        # 实现多账号登录
        if re.match(r'^1[3-9]\d{9}$', username):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'

        # 认证登录用户,验证是否能登录
        user = authenticate(username=username, password=password)
        if not user:
            return http.JsonResponse({'code': 400, 'errmsg': '用户名或密码错误'})

        # 状态保持
        login(request, user)

        # 判断是否记住用户: 没有记住,立刻失效,记住,2周有效
        if remembered:
            request.session.set_expiry(None)
        else:
            request.session.set_expiry(0)

        # 在登录成功后，将用户名写入到cookie，将来会在页面右上角展示
        response = http.JsonResponse({'code': 0, 'errmsg': '注册成功'})
        response.set_cookie('username', user.username, max_age=14 * 24 * 3600)

        # 响应结果
        return response
        # return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


# 用户注册
class RegisterView(View):
    """用户注册
    POST http://www.meiduo.site:8000/register/
    """
    def post(self, request):
        # 接收参数:请求体中的JSON数据
        json_dict = json.loads(request.body.decode())
        # 提取参数
        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        # 提取短信验证码
        sms_code_client = json_dict.get('sms_code')
        allow = json_dict.get('allow')

        # 校验参数
        # 判断是否缺少必传参数
        if not all([username, password, password2, mobile, sms_code_client, allow]):
            return http.JsonResponse({'code': '400', 'errmsg': '缺少必传的参数'})
        # 判断用户名是否满足项目格式要求
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.JsonResponse({'code': '400', 'errmsg': '参数username有误'})
        # 判断password
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'code': '400', 'errmsg': '参数password有误'})
        # 判断password2 和 password
        if password != password2:
            return http.JsonResponse({'code': 400, 'errmsg': '两次输入不对'})
        # mobile检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': 'mobile格式有误'})

        # 判断短信验证码是否正确
        # 提取服务端存储的短信验证码
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if not sms_code_server:
            return http.JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})
        if sms_code_client != sms_code_server.decode():
            return http.JsonResponse({'code': 400, 'errmsg': 'mobile格式有误'})

        # allow检验
        if allow != True:
            return http.JsonResponse({'code': 400, 'errmsg': 'allow格式有误'})

        # 实现核心逻辑:保存注册数据到用户数据表
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '注册失败'})

        # 实现状态保持
        login(request, user)

        # # 在注册成功后，将用户名写入到cookie，将来会在页面右上角展示
        response = http.JsonResponse({'code': 0, 'errmsg': '注册成功'})
        response.set_cookie('username', user.username, max_age=14 * 24 * 3600)

        # 拼接json返回
        return response
        # return http.JsonResponse({'code': 400, 'errmsg': '注册成功'})


# 用户名是否重复注册
class UserCountView(View):
    """用户名是否重复注册
    GET http://www.meiduo.site:8000/usernames/itcast/count/
    """
    def get(self, request, username):
        try:
            # 查询用户名的个数
            count = User.objects.filter(username=username).count()
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})
        # 返回结果
        return http.JsonResponse({'code': '0', 'errmsg': 'OK', 'count': count})


# 手机号是否重复注册
class MobileCountView(View):
    """手机号是否重复注册
    GET http://www.meiduo.site:8000/mobiles/18646794341/count/
    """
    def get(self, request, mobile):
        try:
            # 查询手机号对应的记录
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})
        # 返回结果
        return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})